import axios from 'axios'
import {loadInterceptors} from './loadInterceptors'

//config生成新的axios实例的配置；interceptors要绑定的拦截器；
//requestMethods在实例上绑定的自定义方法数组
export function createAxios({
                       config, interceptors, requestMethods
                     }) {
  //创建axios实例
  const httpRequest = axios.create(config)
  //加载拦截器，并绑定到对于的axios实例
  loadInterceptors(httpRequest, interceptors)
  //遍历方法数组
  for(let method of requestMethods) {
    if(method === 'upload') {
      httpRequest['$Upload'] = requestMethodCreator('post')
      continue
    }
    if(method === 'delete') {
      httpRequest['$' + method.toUpperCase()] = requestMethodCreator(method, {
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
      })
      continue
    }
    httpRequest['$' + method.toUpperCase()] = requestMethodCreator(method)
  }
  return httpRequest
}

//导出请求方法创建器
function requestMethodCreator(method, outConfig) {
  return function baseRequestMethod(API, body, option = {}) {
    let { beforeRequest, onRequest, atferRequest, ...innerConfig } = option
    //写一个自己的拦截器
    const defaultConfig = {
      method,
      url: API,
    }
    //选择请求体
    defaultConfig[method === 'get'? 'params' : 'data'] = body
    //合并配置
    Object.assign(defaultConfig, innerConfig, outConfig)
    //执行自定义拦截
    beforeRequest && beforeRequest()
    let result = this(defaultConfig)
    //真正发送请求
    if(onRequest) {
      result = result.then(onRequest, errorReason => Promise.reject(errorReason))
      if(atferRequest) {
        result = result.finally(atferRequest)
      }
    }
    return result
  }
}
